import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, Drawer, message, Popconfirm } from 'antd';
import { useRequest } from 'umi';
import AuditForm from './AuditForm'; // 引入表单组件
import { fetchAuditList, deleteAudit,detailAudit, withdraw} from '@/services/ant-design-pro/audit'; 
import { useAccess } from 'umi';
import { useModel } from '@umijs/max';

const AuditList: React.FC = (auditType) => {
  const { initialState } = useModel('@@initialState');
const { currentUser } = initialState || {};
  const access = useAccess();
  const actionRef = useRef();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState(null);
  const [isEditMode, setIsEditMode] = useState(false);
  const [activeKey, setActiveKey] = useState<string>('');
  const { run: deleteRun } = useRequest(deleteAudit, {
    manual: true,
    onSuccess: () => {
      message.success('删除成功');
      actionRef.current?.reload();
    },
    onError: () => {
      message.error('删除失败');
    },
  });
  const handleCancel = (id) => {
    withdraw(id).then(() => {
      message.success('撤回成功');
      actionRef.current?.reload();
    });
    
    
  };

  console.log(currentUser)
  const columns = [
    { title: '订单编号', dataIndex: 'orderCode' },
    { title: '审核类型', dataIndex: 'flowType', valueEnum: { 2: '改价', 3: '退款' },search:false },
    { title: '流程名称', dataIndex: 'flowName',search: false,hidden:true },
    { title: '发起人', dataIndex: 'submitName' },
    { title: '原始金额', dataIndex: 'orderAmount',search: false, hidden:auditType.auditType==3?true:false },
    { title: '修改后金额', dataIndex: 'editOrderAmount',search: false,hidden:auditType.auditType==3?true:false },
    { title: '审核人名称', dataIndex: 'auditName',search: false,hidden:true },
    { title: '原始金额', dataIndex: 'orderAmount',search: false,hidden:true },
    { title: '修改后金额', dataIndex: 'editOrderAmount',search: false,hidden:true },
    { title: '审核状态', dataIndex: 'auditStatus', valueEnum: { 20: '待审核', 21: '已审核',22: '已驳回' ,19:'已撤销'},search: false  },
    { title: '审核时间', dataIndex: 'auditTime1', valueType: 'dateTime',search: false , render: (_, record) => record.auditTime1 ? record.auditTime1 : record.auditTime2 },
    // { title: '流程编码', dataIndex: 'flowCode',search: false },
    { title: '创建时间', dataIndex: 'createTime',search: false },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        //撤销
        currentUser?.userid ===  record.updateId && record.auditStatus === 20  &&<Popconfirm key="cancel" title="确定撤销该审批吗？" onConfirm={() => handleCancel(record.id)}>
          <a >撤销</a>
        </Popconfirm>,
        <a key="edit" onClick={() => handleEdit(record)}>查看</a>,
        access.canAccessMenu({menuCode:'00001201'}) &&  <Popconfirm key="delete" title="确定删除该审批吗？" onConfirm={() => handleDelete(record.id)}>
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];
  
  const getAuditStatusString = (status: number): StepsProps["status"] => {
    console.log(status)
      switch (status) {
          case 20:
              return 'wait';
          case 21:
              return 'process';
          case 22:
              return 'finish';
          case 23:
              return 'error';
          default:
              return 'error';
      }
  }


  const handleEdit = async (record) => {
    const data = await detailAudit(record.id) 
    console.log(data,'data')
    const list = data.data.auditName?.split(',').map(item=>{
      return {title:item}
    })
    const current = data.data.auditName?.split(',').indexOf(data.data.currentAuditRoleName)
    setCurrentRow({...data.data,auditName:list,currentAuditRoleName:current});
    setIsEditMode(true);
    setDrawerVisible(true);
  };

  const handleDelete = (id) => {
    deleteRun(id);
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setCurrentRow(null);
    setIsEditMode(false);
  };

  return (
    <PageContainer header={{ title: '' }}>
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        request={(params)=>fetchAuditList({...params,auditStatus:activeKey,flowType:auditType.auditType})}
        columns={columns}
        toolBarRender={() => [
          // <Button key="add" type="primary" onClick={() => setDrawerVisible(true)}>
          //   添加审批
          // </Button>,
        ]}


        toolbar={{
          menu: {
            type: 'tab',
            activeKey: activeKey,
            items: [
              { key: "", label: <span>全部</span> },
              { key: "20", label: <span>待审核</span> },
              { key: "21", label: <span>已审核</span> },
              { key: "22", label: <span>已驳回</span> },
              auditType.auditType==2? { key: "19", label: <span>已撤销</span> }: {},
      
            ],
            onChange: (key) => {
              setActiveKey(key as string);
              actionRef.current?.reloadAndRest();
            },
          },
        }}

      />
      <Drawer
        title={isEditMode ? '审批详情' : '添加审批'}
        width={1200}
        open={drawerVisible}
        onClose={handleDrawerClose}
      >
        <AuditForm
          initialValues={currentRow}
          isEditMode={isEditMode}
          onClose={handleDrawerClose}
          onSuccess={() => actionRef.current?.reload()}
        />
      </Drawer>
    </PageContainer>
  );
};

export default AuditList;